package com.klikmee.sms.core.base.communicator.vip;

import java.text.MessageFormat;

import javax.persistence.NoResultException;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.communicator.AbstractDeliveryReport2MessageResolver;
import com.klikmee.sms.core.base.communicator.DeliveryReport;
import com.klikmee.sms.core.base.exceptions.DeliveryReportNotResolvedException;
import com.klikmee.sms.core.commons.exceptions.ErrorInfo;
import com.klikmee.sms.core.model.OutgoingMessage;

/**
 * Delivery report resolver for vip operator.
 * 
 * @author makcro
 */
public class VipDeliveryReport2MessageResolverImpl extends AbstractDeliveryReport2MessageResolver{

	/**
	 * Init logger instance
	 */
	private Logger logger = Logger.getLogger( VipDeliveryReport2MessageResolverImpl.class );
	/**
	 * Resolves outgoing message by providers message id.
	 * @param deliveryReport carrier for the delivery report information.
	 * @return resolved delivery report
	 * @throws DeliveryReportNotResolvedException 
	 */
	@Override
	public OutgoingMessage resolve(DeliveryReport deliveryReport) throws DeliveryReportNotResolvedException {
		
		try {
			OutgoingMessage sentMessage = this.outgoingMessageDAO.findByProvidersMessageIdAndProvider(deliveryReport.getProvidersMessageId(), deliveryReport.getProvider());
			logger.info( MessageFormat.format( "Resolved delivery report to outgoing messgage id = [{0}]", sentMessage.getId() ) );
			
			return sentMessage;
		} catch (NoResultException e) {
			DeliveryReportNotResolvedException deliveryReportNotResolvedException = new DeliveryReportNotResolvedException();
			ErrorInfo errorInfo = deliveryReportNotResolvedException.addInfo();
			errorInfo.getParameters().put("ProvidersMessageId", deliveryReport.getProvidersMessageId());
			
			throw deliveryReportNotResolvedException;
		}		
	}

}
